/**
 * 事故单详情
 */

import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import React, { useState, useCallback, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import { Row, Col, Button, Card, Tabs, message } from 'antd';
import styles from './index.less';
import moment from 'moment';
import router from 'umi/router';

import {
  getPkgAccidentDetail,
  batchUpdateImg
} from './service';
import {
  Const
} from '../Const';

const { TabPane } = Tabs;

import AuthComponent from '@/components/Authorized/AuthComponent';
import InfoBox from './components/InfoBox';
import CommunicationBox from '../accidentDetail/components/CommunicationBox';
import ImageBox from '../accidentDetail/components/ImageBox';
import PicUpload from '../lessBaggageManagement/components/PicUpload';
import ShowPic from '../lessBaggageManagement/components/ShowPic';

class PrivateData {
  static accidentTypeMap = new Map()
    .set(1, '破损')
    .set(2, '少收')
    .set(3, '多收')
    .set(6, '内物缺失');
  static btnArr = [
    { text: '修改', value: 1, authCode: ['changeIncident', 'changeAllIncident'] },
  //  { text: '临时赔偿', value: 2 },
  //  { text: '结案赔偿', value: 3 },
    { text: '图片管理', value: 4, authCode: ['basicPermissions'] },
  //  { text: '打印', value: 5 },
  ];
}

const AccidentDetail = props => {

  const { location: { state } } = props;

  const [contactInfos, setContactInfos] = useState({}); // 沟通记录
  const [detailInfo, setDetailInfo] = useState({}); // 详情
  const [overchargeRecipient, setOverchargeRecipient] = useState({}); // 收件信息
  const [pkgImgList, setPkgImgList] = useState({}); // 图片

  const [lostItemPicVisible, handleLostItemPicVisible] = useState(false); // PicUpload
  const [lostItemPicManageVisible, handleLostItemPicManageVisible] = useState(false); // ShowPic
  // 是否有图片
  const [lostItemPic, handleLostItemPicture] = useState({
    goodFileList: [],
    touristFileList: [],
    paperFileList: [],
    luggageFileList: []
  });
  // 初始图片数组
  const [originPicArr, handleOriginPicArr] = useState([]);

  // 事故单详情
  const { run: runGetPkgAccidentDetail } = useRequest(params => getPkgAccidentDetail(params), {
    manual: true,
    onSuccess (res) {
      console.log(res, '事故单详情');
      let data = res || {};
      setContactInfos(data.contactInfos || []);
      setDetailInfo(data.pkgAccidentDetailInfoVo || {});
      setOverchargeRecipient(data.overchargeRecipient || {});
      let imgArr = data.pkgImgList || [];
      setPkgImgList(imgArr);
      handleOriginPicArr(imgArr);
      let goodFileListData = imgArr.filter(item => {
        return item.oneType === 1
      });

      let touristFileListData = imgArr.filter(item => {
        return item.oneType === 2
      });

      let paperFileListData = imgArr.filter(item => {
        return item.oneType === 3
      });

      let luggageFileListData = imgArr.filter(item => {
        return item.oneType === 4
      });

      handleLostItemPicture({
        goodFileList: goodFileListData,
        touristFileList: touristFileListData,
        paperFileList: paperFileListData,
        luggageFileList: luggageFileListData,
      });
    }
  });

  const getDetail = useCallback(() => {
    runGetPkgAccidentDetail({
      accidentId: state.accidentId || ''
    })
  }, [state]);

  useEffect(() => {
    getDetail();
  }, [state]);

  // 批量修改图片
  const { run: runBatchUpdateImg } = useRequest(data => batchUpdateImg(data), {
    manual: true,
    onSuccess (res) {
      console.log(res, '批量修改图片');
      getDetail();
      handleLostItemPicManageVisible(false);
      handleLostItemPicVisible(false);
    }
  })

  // 新增图片、改变图片
  const handleImgs = async fields => {

    let img = []
    let obj = {};

    for (let category in fields) {
      fields[category].forEach(imgInfo => {
        imgInfo.relevance = detailInfo.accidentId
        img.push(imgInfo)
      })
    }

    // 修改后带有id(原本存在后台)的图片
    let lostItemPicIdArr = img.filter(item => {
      return item.id
    })
    // 新增加的图片
    let lostItemPicNotIdArr = img.filter(item => {
      return !item.id
    })
    // 找到被删除图片加上remark:1
    let updateArr = originPicArr.concat(lostItemPicIdArr).filter(function (v, i, arr) {
      if (arr.indexOf(v) === arr.lastIndexOf(v)) {
        v.remark = 1
      }
      return arr
    });
    // 去重
    updateArr = updateArr.reduce(function (item, next) {
      obj[next.id] ? '' : obj[next.id] = true && item.push(next);
      return item;
    }, []);

    runBatchUpdateImg([...updateArr, ...lostItemPicNotIdArr])
  };

  // 删除图片
  const handleDelImgs = async fields => {
    let img = []
    let obj = {};
    for (let category in fields) {
      fields[category].forEach(imgInfo => {
        img.push(imgInfo)
      })
    }

    // 找到被删除图片加上remark:1
    let updateArr = originPicArr.concat(img).filter(function (v, i, arr) {
      if (arr.indexOf(v) === arr.lastIndexOf(v)) {
        v.remark = 1
      }
      return arr
    });
    // 去重
    updateArr = updateArr.reduce(function (item, next) {
      obj[next.id] ? '' : obj[next.id] = true && item.push(next);
      return item;
    }, []);

    runBatchUpdateImg([...updateArr]);
  }

  const btnClickMethod = useCallback(item => {
    if (item.value === 1) {
      if (detailInfo.status === '2') {
        router.push({
          pathname: Const.commonUrl + '/inPortBaggageManagement/addEditIncidentMore',
          state: {
            type: 'edit',
            ownerType: state.ownerType,
            isHave: false,
            accidentId: state.accidentId
          }
        });
      } else {
        message.warning('待处理的事故单才能进行修改');
      }
    }
    if (item.value === 4) {
      handleLostItemPicManageVisible(true);
    }
  }, [state, detailInfo]);

  return (
    <div className={styles.accidentDetailContent}>
      <Row className={styles.topBox}>
        <Col span={24} style={{ paddingLeft: '10px' }}>
          <Row style={{ height: '40px', lineHeight: '40px' }}>
            <Col span={14}>
              <div style={{ color: '#000000', fontWeight: 'bold' }}>多收行李运输事故单</div>
            </Col>
            <Col span={10}>
              {PrivateData.btnArr.map((item, index) => {
                let isShow = false;
                const ownerType = +state.ownerType;
                for (let authItem of item.authCode) {
                  if (AuthComponent.getAuth(Const.permissionsType.get(ownerType) + '.' + authItem)) {
                    isShow = true;
                    break;
                  }
                }
                if (item.value === 1 && isShow) {
                  if (detailInfo.status === '2') {
                    return <Button
                      type="primary"
                      key={index}
                      onClick={() => btnClickMethod(item)}
                      disabled={state.ownerType === 3 && (item.value === 2 || item.value === 3)}
                      style={{ marginRight: '10px' }}>
                      {item.text}
                    </Button>
                  }
                }
                if (item.value === 4 && isShow) {
                  return <Button
                    type="primary"
                    key={index}
                    onClick={() => btnClickMethod(item)}
                    disabled={state.ownerType === 3 && (item.value === 2 || item.value === 3)}
                    style={{ marginRight: '10px' }}>
                    {item.text}
                  </Button>
                }
              })}
            </Col>
          </Row>
          <Row style={{ marginTop: '10px' }}>
            <Col span={24}>
              <div>多收编号：{detailInfo.accidentId || ''}</div>
              <div>WT编号：{detailInfo?.pkgDetailInfoList && detailInfo?.pkgDetailInfoList.length !== 0 ? (detailInfo?.pkgDetailInfoList[0]?.wtCode || '') : ''}</div>
            </Col>
          </Row>
        </Col>
      </Row>
      <div className={styles.middleContent}>
        <Tabs defaultActiveKey="1">
          <TabPane tab="详情" key="1">
            <InfoBox detailInfo={detailInfo} overchargeRecipient={overchargeRecipient}></InfoBox>
          </TabPane>
          <TabPane tab="沟通记录" key="2">
            <CommunicationBox
              contactInfos={contactInfos}
              getDetail={getDetail}
              detailInfo={detailInfo}
              ownerType={3}>
            </CommunicationBox>
          </TabPane>
          <TabPane tab="图片" key="3">
            <ImageBox pkgImgList={pkgImgList}></ImageBox>
          </TabPane>
        </Tabs>
      </div>
      <div className={styles.footerBtn}>
        <Button type="primary" onClick={() => {router.goBack()}}>返回</Button>
      </div>
      {lostItemPicVisible && <PicUpload
        onSubmit={async value => {
          const success = await handleImgs(value)
        }}
        onCancel={() => handleLostItemPicVisible(false)}
        lostItemPicVisible={lostItemPicVisible}
        lostItemPic={lostItemPic}
        ownerType={state.ownerType}
      ></PicUpload>}
      {lostItemPicManageVisible && <ShowPic
        onSubmit={async value => {
          const success = await handleDelImgs(value)
        }}
        toUpload={(value) => {
          handleLostItemPicture(value)
          handleLostItemPicManageVisible(false)
          handleLostItemPicVisible(true)
        }}
        onCancel={() => handleLostItemPicManageVisible(false)}
        lostItemPicManageVisible={lostItemPicManageVisible}
        lostItemPic={lostItemPic}
        ownerType={state.ownerType}
        status={detailInfo.status}
      ></ShowPic>}
    </div>
  )
};

export default AccidentDetail;
